package com.igeek.dao;

import com.igeek.domain.User;
import com.igeek.utils.JDBCTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class Userdao {
    QueryRunner qr =new QueryRunner(JDBCTools.getDataSource());
    String sql="";
    public void regist(User user) {
        sql="insert into user values(?,?,?,?,?,?,?,?,?,?)";
        try {
            qr.update(sql,user.getUid(),user.getUsername(),user.getPassword(),
                    user.getName(),user.getEmail(),user.getTelephone(),
                    user.getBirthday(),user.getSex(),user.getState(),
                    user.getCode());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean checkactiveCode(String activeCode) {
        sql = "select * from user where code = ?";
        User u =null;
        try {
            u = qr.query(sql,new BeanHandler<>(User.class),activeCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u!=null?true:false;
    }

    public void updateactiveCode(String activeCode) {
        sql="update user set state = 1 where code = ? ";
        try {
            qr.update(sql,activeCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public User login(User user) {
        sql ="select * from user where username = ? and password = ? and state = 1";
        User u = null;
        try {
            u = qr.query(sql,new BeanHandler<>(User.class),user.getUsername(),user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u;
    }

    public boolean checkname(String username) {
        sql="select * from user where username=?";
        User user=null;
        try {
            user=qr.query(sql,new BeanHandler<>(User.class),username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user!=null?true:false;
    }

}
